package com.fantasyland.backend.Service;

import com.fantasyland.backend.Entity.Post;
import com.fantasyland.backend.Repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class PostService {
    
    @Autowired
    private PostRepository postRepository;
    
    /**
     * 获取所有帖子，按时间倒序
     */
    public List<Post> getAllPosts() {
        return postRepository.findAllByOrderByTimestampDesc();
    }
    
    /**
     * 根据ID获取帖子
     */
    public Optional<Post> getPostById(Long id) {
        return postRepository.findById(id);
    }
    
    /**
     * 创建新帖子
     */
    public Post createPost(Post post) {
        // 设置创建时间
        post.setTimestamp(LocalDateTime.now());
        // 初始化回复数
        if (post.getReplies() == null) {
            post.setReplies(0);
        }
        return postRepository.save(post);
    }
    
    /**
     * 更新帖子
     */
    public Post updatePost(Long id, Post updatedPost) {
        Optional<Post> existingPost = postRepository.findById(id);
        if (existingPost.isPresent()) {
            Post post = existingPost.get();
            post.setTitle(updatedPost.getTitle());
            post.setContent(updatedPost.getContent());
            post.setAuthor(updatedPost.getAuthor());
            return postRepository.save(post);
        }
        throw new RuntimeException("帖子不存在，ID: " + id);
    }
    
    /**
     * 删除帖子
     */
    public void deletePost(Long id) {
        if (postRepository.existsById(id)) {
            postRepository.deleteById(id);
        } else {
            throw new RuntimeException("帖子不存在，ID: " + id);
        }
    }
    
    /**
     * 增加回复数
     */
    public Post incrementReplies(Long id) {
        Optional<Post> postOptional = postRepository.findById(id);
        if (postOptional.isPresent()) {
            Post post = postOptional.get();
            post.setReplies(post.getReplies() + 1);
            return postRepository.save(post);
        }
        throw new RuntimeException("帖子不存在，ID: " + id);
    }
    
    /**
     * 根据作者查询帖子
     */
    public List<Post> getPostsByAuthor(String author) {
        return postRepository.findByAuthorOrderByTimestampDesc(author);
    }
    
    /**
     * 根据标题搜索帖子
     */
    public List<Post> searchPostsByTitle(String title) {
        return postRepository.findByTitleContainingIgnoreCaseOrderByTimestampDesc(title);
    }
    
    /**
     * 获取最新的N个帖子
     */
    public List<Post> getLatestPosts(int limit) {
        return postRepository.findLatestPosts(limit);
    }
}